import json
import logging
import uuid

from utils import db_util
from controller import base_handler


class ListHandler(base_handler.BaseHandler):
    def get(self):

        page = self.get_query_argument("page", "1")
        perPage = self.get_query_argument("perPage", "100")
        orderBy = self.get_query_argument("orderBy", "res_code")
        orderDir = self.get_query_argument("orderDir", "asc")

        params = []
        where_sql = " where"
        for field_name in ("system_id", "module_id"):
            field_value = self.get_query_argument(field_name, None)
            if field_value:
                params.append(field_value)
                where_sql += " cr.%s = ? and" % field_name

        for field_name in ("res_code", "res_name", "res_desc",):
            field_value = self.get_query_argument(field_name, None)
            if field_value:
                params.append("%" + field_value + "%")
                where_sql += " cr.%s like ? and" % field_name

        sql = """select cr.*,cs.sys_name,cm.m_name from crud_resource cr left join crud_system cs on cs.id=cr.system_id left join crud_module cm on cm.id=cr.module_id """
        if len(params) > 0:
            sql += where_sql[0:-3]
        else:
            params = None

        sql += " order by %s %s" % (orderBy, orderDir)
        rows = db_util.execute_page(sql, int(page), int(perPage), params)
        for row in rows["items"]:
            resource_id = row["id"]
            sql = """select count(*) from crud_interface  where resource_id=? """
            tmp_row = db_util.fetchone(sql, [resource_id])
            row["interface_count"] = tmp_row[0]

        res = {"status": 0, "message": "ok",
               "data": {"page": page, "total": rows["total"], "rows": rows["items"]}}

        self.set_response(res, 200)


class SelectHandler(base_handler.BaseHandler):
    def get(self):
        system_id = self.get_query_argument("system_id", None)
        if system_id is None:
            res = {"status": 0, "message": "ok", "data": {"options": []}}
            self.set_response(res, 200)
            return
        module_id = self.get_query_argument("module_id", None)
        if system_id is None:
            res = {"status": 0, "message": "ok", "data": {"options": []}}
            self.set_response(res, 200)
            return

        sql = """select id,res_code,res_name from crud_resource where system_id=? and module_id=? order by res_code """
        rows = db_util.fetchall(sql, [system_id, module_id])
        options = []
        for row in rows:
            options.append({"value": row[0], "label": row[2], "res_code": row[1]})

        res = {"status": 0, "message": "ok", "data": {"options": options}}

        self.set_response(res, 200)


class AddHandler(base_handler.BaseHandler):
    @staticmethod
    def resource_count(system_id, module_id, res_code):

        sql = """ select count(*) as count from  crud_resource where system_id=? and module_id=? and res_code=?"""
        row = db_util.fetchone(sql, params=[system_id, module_id, res_code])
        return row[0]

    def post(self):
        logging.info(self.request.body.decode())
        req_body = json.loads(self.request.body.decode())

        m_id = uuid.uuid1().hex
        system_id = req_body.get("system_id", None)
        module_id = req_body.get("module_id", None)
        res_code = req_body.get("res_code", None)
        res_name = req_body.get("res_name", None)
        res_desc = req_body.get("res_desc", None)

        count = AddHandler.resource_count(system_id, module_id, res_code)
        if count > 0:
            res = {"status": 1, "message": "添加失败：资源编号重复[%s]" % res_code}
            self.set_response(res, 200)
            return

        sql = """ insert into crud_resource (id,system_id,module_id,res_code,res_name,res_desc)values(?,?,?,?,?,?)"""
        param = [m_id, system_id, module_id, res_code, res_name, res_desc]
        flag = db_util.execute_update(sql, params=param)
        if flag is True:
            res = {"status": 0, "message": "添加成功"}
        else:
            res = {"status": 1, "message": "添加失败:%s" % db_util.get_last_error()}

        self.set_response(res, 200)


class EditHandler(base_handler.BaseHandler):
    def post(self):
        logging.info(self.request.body.decode())
        req_body = json.loads(self.request.body.decode())
        res_id = req_body.get("id", None)
        param = []
        up_sql = ""
        for field_name in ("res_code", "res_name", "res_desc",):
            field_value = req_body.get(field_name, None)
            if field_value:
                param.append(field_value)
                up_sql += "%s=?," % field_name
        param.append(res_id)

        sql = """update crud_resource set %s where id=?""" % (up_sql[0:-1])
        flag = db_util.execute_update(sql, param)
        if flag is True:
            res = {"status": 0, "message": "修改成功"}
        else:
            res = {"status": 1, "message": "修改失败:%s" % db_util.get_last_error()}

        self.set_response(res, 200)


class DelHandler(base_handler.BaseHandler):
    def post(self):
        logging.info(self.request.body.decode())
        req_body = json.loads(self.request.body.decode())
        flag = False
        res_id = req_body.get("id", None)

        if res_id and res_id != "":
            sql = "delete from crud_verify where interface_id in (select id from crud_interface where resource_id =?)"
            db_util.execute_update(sql, [res_id])

            sql = "delete from crud_interface where resource_id=?"
            db_util.execute_update(sql, [res_id])

            sql = "delete from crud_resource where id =?"
            flag = db_util.execute_update(sql, [res_id])
        if flag is True:
            res = {"status": 0, "message": "删除成功"}
        else:
            res = {"status": 1, "message": "删除失败:%s" % db_util.get_last_error()}

        self.set_response(res, 200)
